import { EVENTS } from '../..';
import { MODEL_NAME } from '../../constants/model-names';
import { EQUIP_SLOT, type EquipSlot } from '../../data/item/type';
import type { IEventBus } from '../../events';
import type { BaseSnapshot } from '../../systems/save';
import { BaseModel } from '../base';
import type { InventorySlotItem } from '../inventory/type';

export interface EquipmentPanelV1 extends BaseSnapshot {
  version: 1;
  slots: Record<EquipSlot, InventorySlotItem | null>;
}

export type EquipmentPanelSnapshot = EquipmentPanelV1;

export type EquipmentPanelSnapshotOld = EquipmentPanelV1;

export class EquipmentPanelModel extends BaseModel {
  public name = MODEL_NAME.EQUIPMENT_PANEL;
  private bus: IEventBus;
  private slots: Record<EquipSlot, InventorySlotItem | null>;

  constructor(bus: IEventBus) {
    super();
    this.bus = bus;
    this.slots = Object.keys(EQUIP_SLOT).reduce((acc, k) => {
      acc[k as EquipSlot] = null;
      return acc;
    }, {} as Record<EquipSlot, InventorySlotItem | null>);
  }

  public equip(slot: EquipSlot, item: InventorySlotItem | null) {
    this.slots[slot] = item;
    this.bus.emit(EVENTS.EQUIPMENT_PANEL_STATE_UPDATE);
  }

  public unequip(slot: EquipSlot) {
    this.slots[slot] = null;
    this.bus.emit(EVENTS.EQUIPMENT_PANEL_STATE_UPDATE);
  }

  public getSlot(slot: EquipSlot): InventorySlotItem | null {
    return this.slots[slot];
  }

  public getSlots() {
    return this.slots;
  }

  public override load(snapshot: EquipmentPanelSnapshot) {
    this.slots = snapshot.slots;
  }

  public override save(): EquipmentPanelSnapshot {
    return {
      version: 1,
      slots: this.slots,
    };
  }
}
